import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/home_weather_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/main_tabbar/main_tabbar_page.dart';
import 'package:dk_flutter_module_sale/phoenix/tools/page/page_home_all_tools.dart';
import '../bean/ui_const_bean.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dk_flutter_module_sale/portal/api/portal_api.dart';
import '../../../r.dart';
import 'my_work_page.dart';

class HomePage extends CommonPage {
  final EventBus clickTabBarEventBus;
  HomePage(this.clickTabBarEventBus) : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    pageBloc.switchPage(HomeWidget(pageBloc,clickTabBarEventBus));
  }
}

class HomeWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final EventBus clickTabBarEventBus;
  HomeWidget(this.pageBloc,this.clickTabBarEventBus);

  @override
  HomeState createState() {
    return HomeState(this.pageBloc);
  }
}

class HomeState extends State<HomeWidget> with SingleTickerProviderStateMixin {

  CommonPageBloc messageBloc;
  HomeWeatherBean homeWeatherBean;

  HomeState(this.messageBloc);

  var _index = 0;
  var _isPageCanChanged = true;
  TabController _tabController;
  PageController _pageController = PageController(initialPage: 0);

  @override
  void initState() {
    super.initState();
    UserTrack.trackViewScreen("公共首页-新", null);
    _tabController = new TabController(length: 2, vsync: this);
    messageBloc.dataHttpPost(path:PortalApi.homeWeather,
      handleResult: (dynamic data) {
        homeWeatherBean = HomeWeatherBean.fromJson(data);
        setState(() {
        });
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
    widget.clickTabBarEventBus.on<ClickTabBarEvent>().listen((ClickTabBarEvent event){
      if(event.clickPage == TabBarPage.TabBarPageHome) {
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff5f5f5),
      body: Column(
        children: <Widget>[
          Container(
            height: UIConstBean.HomeWeatherH,
            padding: EdgeInsets.only(top: 31,right: 16,left: 16),
            decoration: const BoxDecoration(
               color: Color(0xff3274F9),
               border: Border(bottom: BorderSide(width: 0.0,color: Color(0xff3274F9))),
            ),
            child:  GridView.count(
              crossAxisSpacing: 0.0,
              mainAxisSpacing: 0.0,
              padding: const EdgeInsets.all(0.0),
              crossAxisCount: 2,
              childAspectRatio: 8.0,
              children: <Widget>[
                _buildGridWeatherView(),
                _buildGridDateView(),
              ],
            ),
          ),
          Container(
            height: UIConstBean.HomeTabbarH,
            width: double.infinity,
            decoration: const BoxDecoration(
              color: Color(0xff3274F9),
              border: Border(top: BorderSide(width: 0.0,color: Color(0xff3274F9),),
              bottom: BorderSide(width: 0.0,color: Color(0xff3274F9)),),
            ),

            child: Center(
              child: TabBar(
                onTap: (index){
                  if (!mounted){
                    return;
                  }
                  _pageController.jumpToPage(index);
                },
                isScrollable: true,
                controller: _tabController,
                labelStyle: const TextStyle(
                    fontSize: 20.0,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                ),
                unselectedLabelStyle: const TextStyle(
                    fontSize: 20.0,
                    color: Colors.white,
                    fontWeight: FontWeight.w300
                ),
                indicatorSize: TabBarIndicatorSize.label,
                indicatorColor: Colors.white,
                indicatorWeight: 3,
                unselectedLabelColor: Colors.white,
                labelColor: Colors.white,
                indicatorPadding: const EdgeInsets.only(left: 30.0, right: 30.0,bottom: 7),
                tabs: <Widget>[
                  Tab(text: "我的工作",),
                  Tab(text: "全部工具",),
                ],
              ),
            ),
          ),

          Expanded(
            child: PageView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: 2,
              onPageChanged: (index) {
                if (_isPageCanChanged) {//由于pageview切换是会回调这个方法,又会触发切换tabbar的操作,所以定义一个flag,控制pageview的回调
                  _onPageChange(index);
                }
              },
              controller: _pageController,
              itemBuilder: (BuildContext context, int index) {
                UserTrack.track(index > 0 ? "click_main_all_tools" : "click_main_my_work", null);
                return index > 0 ?  HomeAllToolsPage() : MyWorkPage();
              },
            ),
          )

        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }
  _onPageChange(int index, {PageController page, TabController t}) async {
    if (page!= null) {
      _isPageCanChanged = false;
      await _pageController.animateToPage(index, duration: Duration(milliseconds: 300), curve: Curves.ease);//等待pageview切换完毕,再释放pageivew监听
      _isPageCanChanged = true;
    } else {
      _tabController.animateTo(index);//切换Tabbar
    }
    setState(() {
      _index = index;
    });
  }

  Widget _buildGridWeatherView(){
    return Container(
      color: Colors.transparent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
         children: <Widget>[
           Offstage(
             offstage: homeWeatherBean == null,
             child: Image.asset(R.imagesHomeHomeWeatherPng,width: 16,height: 16,fit:BoxFit.fill,),
           ),
           SizedBox(width: 7,),
           Text(homeWeatherBean!= null ? homeWeatherBean.temperature : '',
             textAlign: TextAlign.left,
             style: TextStyle(color: Color(0xffA5C2FC), fontSize: 12,fontWeight: FontWeight.normal),
           ),
           SizedBox(width: 10,),
           Text(homeWeatherBean!= null ? homeWeatherBean.cityWeather : '',
             textAlign: TextAlign.left,
             style: TextStyle(color: Color(0xffA5C2FC), fontSize: 12,fontWeight: FontWeight.normal),
           ),
         ],
      ),
    );
  }

  Widget _buildGridDateView(){
    return Container(
      color: Colors.transparent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Offstage(
            offstage: homeWeatherBean == null,
            child: Image.asset(R.imagesHomeHomeDatePng,width: 16,height: 16,fit:BoxFit.fill,),
          ),
          SizedBox(width: 3,),
          Text(homeWeatherBean!= null? homeWeatherBean.date : '',
            textAlign: TextAlign.left,
            style: TextStyle(color: Color(0xffA5C2FC), fontSize: 12,fontWeight: FontWeight.normal),
          ),
          SizedBox(width: 3,),
          Text(homeWeatherBean!=null ? homeWeatherBean.banNumber : '',
            textAlign: TextAlign.left,
            style: TextStyle(color: Color(0xffA5C2FC), fontSize: 12,fontWeight: FontWeight.normal),
          ),
        ],
      ),
    );
  }
}
